// how many Facebook messages we have to display
window.nbPosts = 10;
//window.nbShownPosts = 8;
$("#nbposts-slider")[0].value=window.nbPosts;

// demo (avoiding Fb calls)
window.offlineMode = 0;

// Facebook fetching time interval in seconds
window.fbCheckInterval = 30;

// time interval between each Facebook fetching
window.refreshTime = 30;
$("#refresh-slider")[0].value=window.refreshTime;

// show friend links between posts
window.showLinks = 1;

// enable audio
window.enableSound = 0;

// get a random position, different from the other posts
function generatePosition(post) {
  var tab = new Array(); // we return a tab containing the position (x,y) of the new post

  // check if a post from the same author exists
  for (i=0; i<fbPosts.length; i++) {
    var alt=Math.floor(Math.random()*4); // one of the 4 corner of the post
    if (post.get('from_id') == fbPosts.models[i].get('from_id')) {
      if (alt==0) {
        tab[0]=fbPosts.models[i].get('pos_x')+5;
        tab[1]=fbPosts.models[i].get('pos_y')+5;
        return tab;
      }
      if (alt==1) {
        tab[0]=fbPosts.models[i].get('pos_x')-5;
        tab[1]=fbPosts.models[i].get('pos_y')-5;
        return tab;
      }
      if (alt==2) {
        tab[0]=fbPosts.models[i].get('pos_x')+5;
        tab[1]=fbPosts.models[i].get('pos_y')-5;
        return tab;
      }
      if (alt==3) {
        tab[0]=fbPosts.models[i].get('pos_x')-5;
        tab[1]=fbPosts.models[i].get('pos_y')+5;
        return tab;
      }
    }
  }

  // we generate a random position and check if it's not too close 
  // from another post's position
  var close = 1;
  var x;
  var y;
  while (close == 1) {
    close = 0;
    x = Math.floor(Math.random()*71) +15;
    y = Math.floor(Math.random()*71) +15;
    for (i=0;i<fbPosts.length;i++) {
      if (tooClose(fbPosts.models[i].get('pos_x'),x,8)
        && tooClose(fbPosts.models[i].get('pos_y'),y,8)) {
        close = 1;
      }
    }
  }
  tab[0]=x; tab[1]=y;
  return tab;
}

// create a new FBPost from the Facebook response.data
function createFBPost(fbData) {
  // create a new post
  var post = new FBPost();
  // set the post
  if (fbData.id)
    post.set({id: fbData.id});
  if (fbData.message) {
    if(fbData.message.length>100)
      post.set({message: cutMessage(fbData.message.substr(0,101))+' [...]'});
    else
      post.set({message: fbData.message});
  }
  else if (fbData.story)
    post.set({message: fbData.story});
  if (fbData.created_time)
    post.set({time: fbData.created_time});
  if (fbData.likes)
    post.set({likes: fbData.likes.count});
  if (fbData.comments)
    post.set({comments: fbData.comments.count});
  if (fbData.from.id)
    post.set({from_id: fbData.from.id});
  if (fbData.from.name) {
    post.set({from_name: fbData.from.name});
  }
  if (fbData.from.category){
    post.set({from_page: 1});
  }
  // different request for the profile picture
  FB.api('/'+fbData.from.id+'/picture?type=large', 'get', function(response) {
    post.set({from_picture: response.data.url});
  });
  // define a random position
  var xy = generatePosition(post);
  post.set({pos_x: xy[0]});
  post.set({pos_y: xy[1]});

  return post;
}

// change background color while loading
function changeBackground() {
  if ($("#main").hasClass("gradient1")) {
    $("#main").toggleClass("gradient1 gradient2");
    return 2;
  }
  else {
    $("#main").toggleClass("gradient2 gradient1");
    return 1;
  }
};

// Facebook request to download new Facebook news feed posts
function checkFb() {
  changeBackground(); // before loading
  console.log('Fetching last messages... ');
  FB.api('/me/home', 'get', function(response) { //request to get the 25 most recent posts
    if (!response || response.error) {
      console.log(response.error);
      changeBackground();
    } else {

      // delete missing Facebook posts
      for (var i=0; i<fbPosts.length; i++) { // test all FBPosts
        var present=0;
        for (var j=0; j<nbPosts; j++) { // with the request result
          if (fbPosts.at(i).get('id')==response.data[j].id)
            present=1;
        }
        if (present==0) {
          fbPosts.at(i).destroy();
          i--;
        }
      }

      // add new post(s)
      for (var i=0; i<nbPosts; i++) {
        var post = createFBPost(response.data[i]);
        // check if the post is already in the list
        if (fbPosts.isIncluded(post)) {
          // check if the number of likes/comments has been modified
          if (fbPosts.get(post.id).likes != post.likes)
            fbPosts.get(post.id).set({likes: post.likes});
          if (fbPosts.get(post.id).comments != post.comments)
            fbPosts.get(post.id).set({comments: post.comments});
          if (fbPosts.get(post.id).from_picture != post.from_picture)
            fbPosts.get(post.id).set({from_picture: post.from_picture});
        }
        else {
          if (fbPosts.length>=nbPosts) {
            fbPosts.getOlder().destroy();
          }
          fbPosts.add(post); 
        }
      }
    }
    // after loading
    changeBackground();
    setFriendRelations(); // cannot be used
  });
}

// check Facebook news feed every <interval> seconds
function checkFbEvery(interval) {
  window.fbCheckInterval = setInterval(function() {
    if (window.enableFBChecking==1)
      checkFb();
  }, interval*1000);
}

// check if two people are Fb friends using their Fb ID
function areFriends(post1,post2,callback) {
  FB.api('/'+post1.get('from_id')+'/friends/'+post2.get('from_id'), 'get', function(response) {
    if (!response || response.error) {
      console.log(response.error);
    } else {
      if (response.data.length > 0) {
        callback(1, post1, post2);
      }
      else
        callback(0, post1, post2);
    }
  });
}

// record all friends relations // idée abandonnée, dû au temps de réponse des requêtes facebook trop important
window.friendRelations = new Array(21);
for (i=0; i<friendRelations.length; i++) friendRelations[i] = new Array(21);

function compareOnePost(postId) {
  var tab = new Array();

}

function setFriendRelations() {
  for (i=0; i<fbPosts.models.length; i++) {
    var tempPost1 = fbPosts.at(i);
    for (j=0; j<fbPosts.models.length; j++) {
      var tempPost2 = fbPosts.models[j];
      areFriends(tempPost1, tempPost2, function(yesOrNo, post1, post2) {
        friendRelations[fbPosts.indexOf(post1)][0] = post1.get('id');
        if (yesOrNo == 1) {
          friendRelations[fbPosts.indexOf(post1)][fbPosts.indexOf(post2)+1] = post2.get('id');
        }
        else
          friendRelations[fbPosts.indexOf(post1)][fbPosts.indexOf(post2)+1] = -1;
      });
    }
  }
}

/*function setFriendRelations() {
  var wait=0; // wait for the end of the Facebook request
  for (i=0; i<fbPosts.models.length; i++) {
    var tempId1 = fbPosts.at(i).get('from_id');
    for (j=0; j<fbPosts.models.length; j++) {
      var tempId2 = fbPosts.models[j].get('from_id');
      areFriends(tempId1, tempId2, function(response) {
        if (response == 1) {
          friendRelations[i][0] = tempId1;
          friendRelations[i][j+1] = tempId2;
        }
        else
          friendRelations[i][j+1] = -1;
        console.log("["+i+"][0]="+tempId1);
        console.log("["+i+"]["+j+1+"]="+tempId2);
      });
    }
  }
}*/


// samples for the demo mode
window.samples = [
    { id:"01", message:"I'm trying to make the world a more open place.", likes:35, comments:0, from_id:01,
      from_name:"Mark Zuckerberg", from_picture:"img/test-pic1.jpg", pos_x:"54", pos_y:"80"},
    { id:"02", message:"The Arc of the moral universe is long, but it bends towards justice.", likes:25, comments:4, from_id:02,
      from_name:"Barack Obama", from_picture:"img/test-pic2.jpg", pos_x:"12", pos_y:"59"},
    { id:"03", message:"Le changement c'est maintenant.", likes:56, comments:15, from_id:03,
      from_name:"François Hollande", from_picture:"img/test-pic3.jpg", pos_x:"35", pos_y:"53"},
    { id:"04", message:"I'm lovin' it.", likes:15, comments:0, from_id:04,
      from_name:"McDonald's", from_picture:"img/test-pic4.jpg", from_page:1, pos_x:"86", pos_y:"46"},
    { id:"05", message:"Mr Bean shared a link.", likes:6, comments:0, from_id:05,
      from_name:"Mr Bean", from_picture:"img/test-pic5.jpg", pos_x:"15", pos_y:"33"},
    { id:"06", message:"Maintenant en DVD et Blu-Ray.", likes:1900, comments:0, from_id:06,
      from_name:"The Dark Knight Rises", from_picture:"img/test-pic6.jpg", from_page:1, pos_x:"67", pos_y:"35"},
    { id:"07", message:"On en a gros !", likes:2, comments:13, from_id:07,
      from_name:"Sir Perceval", from_picture:"img/test-pic7.jpg", pos_x:"78", pos_y:"67"},
    { id:"08", message:"Vous pouvez répéter la question ?", likes:4, comments:5, from_id:08,
      from_name:"Alain Deloin", from_picture:"img/test-pic8.jpg", pos_x:"16", pos_y:"18"}
  ];

// manage the demo mode
function startDemo() {
  window.offlineMode = 1;
  $("#connect-form").toggleClass("visible hidden");
  $("#demo-form").toggleClass("visible hidden");
  for(i=0;i<nbPosts;i++) {
    fbPosts.add(samples[i]);
  }
}

